package com.wxt.blog.controller;

import com.wxt.blog.entity.Comment;
import com.wxt.blog.entity.User;
import com.wxt.blog.service.CommentService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/comment/*")
public class CommentController extends HttpServlet {
    private final CommentService commentService = new CommentService();

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getRequestURI().substring(req.getContextPath().length());

        // 判断请求路径是否为添加评论的路径
        if ("/comment/add".equals(path)) {
            User user = (User) req.getSession().getAttribute("user");

            // 如果用户未登录，重定向到登录页面
            if (user == null) {
                resp.sendRedirect(req.getContextPath() + "/login.jsp");
                return;
            }

            Comment comment = new Comment();
            comment.setContent(req.getParameter("content"));
            comment.setUserId(user.getId());
            comment.setBlogId(Integer.parseInt(req.getParameter("blogId")));

            commentService.addComment(comment);
            resp.sendRedirect(req.getContextPath() + "/blog/detail?id=" + comment.getBlogId());
        }
    }
}